package com.tarena.lbs.business.service.impl;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

// 添加ZXing库的必要导入
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;


public class QRCodeUtil {
    // 二维码颜色
    private static final int BLACK = 0xFF000000;
    // 二维码背景色
    private static final int WHITE = 0xFFFFFFFF;
    // 二维码宽度
    private static final int WIDTH = 300;
    // 二维码高度
    private static final int HEIGHT = 300;

    /**
     * 生成二维码图片
     * @param content 二维码内容
     * @return 图片字节数组
     */
    public static byte[] generateQRCode(String content) throws Exception {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 字符编码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 容错等级(L < M < Q < H)
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 边距
        hints.put(EncodeHintType.MARGIN, 1);

        // 生成二维码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(
                content,
                BarcodeFormat.QR_CODE,
                WIDTH,
                HEIGHT,
                hints
        );

        // 转换为BufferedImage
        BufferedImage image = toBufferedImage(bitMatrix);

        // 转换为字节数组
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", outputStream);
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new Exception("生成二维码失败", e);
        }
    }

    /**
     * 将BitMatrix转换为BufferedImage
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }

        return image;
    }

    /**
     * 生成带logo的二维码
     * @param content 二维码内容
     * @param logoImage logo图片
     * @return 图片字节数组
     */
    public static byte[] generateQRCodeWithLogo(String content, BufferedImage logoImage) throws Exception {
        // 先生成基础二维码
        byte[] qrCodeBytes = generateQRCode(content);
        BufferedImage qrImage = ImageIO.read(new java.io.ByteArrayInputStream(qrCodeBytes));

        // 添加logo
        Graphics2D g = qrImage.createGraphics();

        // logo大小为二维码的1/5
        int logoWidth = logoImage.getWidth(null) > qrImage.getWidth() / 5 ?
                (qrImage.getWidth() / 5) : logoImage.getWidth(null);
        int logoHeight = logoImage.getHeight(null) > qrImage.getHeight() / 5 ?
                (qrImage.getHeight() / 5) : logoImage.getHeight(null);

        // 计算logo位置（居中）
        int x = (qrImage.getWidth() - logoWidth) / 2;
        int y = (qrImage.getHeight() - logoHeight) / 2;

        // 绘制logo
        g.drawImage(logoImage, x, y, logoWidth, logoHeight, null);

        // 给logo加边框
        g.setStroke(new BasicStroke(2));
        g.setColor(Color.WHITE);
        g.drawRect(x, y, logoWidth, logoHeight);

        g.dispose();
        logoImage.flush();
        qrImage.flush();


        File outputFile = new File("F:/qrcode/logo.jpg");
        ImageIO.write(qrImage,"png",outputFile);

        // 转换为字节数组
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIO.write(qrImage, "png", outputStream);
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new Exception("生成带logo的二维码失败", e);
        }
    }
}
